package cn.itcast.demo;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;

public class ServletConfigDemo extends HttpServlet {
//    声明ServletConfig对象
    private ServletConfig config;
//    重写init方法 对ServletConfig赋值

    @Override
    public void init(ServletConfig config) throws ServletException {
        this.config = config;
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//          演示ServletConfig常用方法
//        根据key获取value
        String encodingValue = config.getInitParameter("encoding");
        System.out.println(encodingValue);
//        获取所有的key
        Enumeration<String> names = config.getInitParameterNames();
        while (names.hasMoreElements()){
//            获取每一个key
            String key = names.nextElement();
//            根据key获取value
            String value = config.getInitParameter(key);
            System.out.println(key + "...." + value);
        }
//        获取ServletConfig名称
        String servletName = config.getServletName();
        System.out.println(servletName);
//        获取ServletContext对象
        ServletContext servletContext = config.getServletContext();
        System.out.println(servletContext);
        Object username = servletContext.getAttribute("username");
        System.out.println(username);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}
